/**
 * dbms-sjtu
 * Schma.java created at Jul 22, 2011
 */
package dbms.record;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import dbms.Constants;

/**
 * @author weapon
 * the table's schema, use HashMap to manage
 */
public class Schema {
	public String primaryKeyField = null;
	
	private int count = 0;
	private Map<String, Integer> fieldRank = new HashMap<String, Integer>();
	
	private  Map<String, FieldInfo> info = new HashMap<String, FieldInfo>();
	
	public void addField(String fieldName, FieldInfo fieldInfo){
		fieldRank.put(fieldName, count);
		count++;
		info.put(fieldName, fieldInfo);
	}
	
	public void addField(String fieldName, int type, int length) {
		fieldRank.put(fieldName, count);
		count++;
		info.put(fieldName, new FieldInfo(type, length));
	}
	
	public void addIntField(String fieldName){
		addField(fieldName, Constants.INTEGER, Constants.INT_SIZE);
	}
	
	public void addStrField(String fieldName, int length){
		addField(fieldName, Constants.VARCHAR, length);
	}
	
	public boolean hasField(String fieldName){
		return info.containsKey(fieldName);
	}
	
	/**
	 * add the schema's all field to this schema
	 * @param schema
	 */
	public void addAll(Schema schema){
		for(String field : schema.getInfo().keySet()){
			this.info.put(field, schema.getInfo().get(field));
		}
	}
	
	/**
	 * add a field to this schema, which field info is same as another field in @param schema
	 * @param field
	 * @param schema
	 */
	public void add(String field, Schema schema){
		this.addField(field, schema.getInfo().get(field));
	}
	
	/**
	 * for iterator all fields
	 * @return the set of key
	 */
	public Collection<String> fields(){
		return info.keySet();
	}
	
	public int type(String fieldName){
		return info.get(fieldName).type;
	}
	
	public int length(String fieldName){
		return info.get(fieldName).length;
	}
	
	public Map<String, FieldInfo> getInfo(){
		return this.info;
	}
	
	public Map<String, Integer> getFieldRank(){
		return this.fieldRank;
	}
}
